import { Logger, Module } from '@nestjs/common';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AgentModule } from './api/agent/agent.module';
import { DocumentModule } from './api/document/document.module';
import { StoreModule } from './api/store/store.module';
import { UserModule } from './api/user/user.module';
import { PostModule } from './api/post/post.module';
import { AuthModule } from './api/auth/auth.module';
import { StorageModule } from './api/storage/storage.module';

import { AllExceptionFilter } from './core/filter/all-exception.filter';
import { TransformInterceptor } from './core/interceptor/transform.interceptor';

import { JwtAuthGuard } from './core/guard/jwt.guard';

import { User } from './api/user/entities/user.entity';
import { Post } from './api/post/entities/post.entity';
import { Store } from './api/store/entities/store.entity';
import { Storage } from './api/storage/entities/storage.entity';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql', // 数据库类型
        entities: [Post, Store, User, Storage], // 数据表实体
        host: configService.get<string>('DB_HOST'),
        port: configService.get<number>('DB_PORT'),
        username: configService.get<string>('DB_USER'),
        password: configService.get<string>('DB_PASSWORD'),
        database: configService.get<string>('DB_DATABASE'),
        timezone: '+08:00', //服务器上配置的时区
        charset: 'utf8mb4',
        synchronize: true, //根据实体自动创建数据库表， 生产环境建议关闭
      }),
    }),
    AgentModule,
    DocumentModule,
    StoreModule,
    UserModule,
    PostModule,
    AuthModule,
    StorageModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    Logger,
    { provide: APP_FILTER, useClass: AllExceptionFilter },
    { provide: APP_INTERCEPTOR, useClass: TransformInterceptor },
    { provide: APP_GUARD, useClass: JwtAuthGuard },
  ],
})
export class AppModule {}
